import Taro, {Component, Config} from "@tarojs/taro";
import { View, Text, Image, RichText } from "@tarojs/components";
import { AtCurtain } from 'taro-ui'
import {IStoreProps} from '../../store/Stores';
import {getRuntime, subtime, ServerHost, partOf, htmlToText, wxShare} from '../../utils/common';
// import {WxShare} from '../../utils/shareH5Server';
import {toJS} from "mobx";
import {inject, observer} from "@tarojs/mobx";

import './detail.less'
import iconCollection from '../../assets/img/icon_03.png'
import iconCollection_on from '../../assets/img/icon_03_on.png'
import iconShare from '../../assets/img/icon_04.png'
import share_icon from "../../assets/img/share_arrow.png";
import close_icon from "../../assets/img/icon_close_bold.png";


interface IHomeProps extends IStoreProps {}
@inject("stores")
@observer
class Detail extends Component<IHomeProps>{
  constructor(props){
    super(props)
  }

  state = {
    item: {},
    isCollection: false,
    isTips: false,
    tipsText: '',
    wxConfig: {},
    isShare: false
  }

  componentWillMount() {
    Taro.setNavigationBarTitle({title: '动态详情'})
    this.getJsApiParam()
    this.getDynamicInfo(this.$router.params.id)
    let isCollection = parseInt(this.$router.params.isCollection)
    if(isCollection===1){ this.setState({ isCollection: true }) }
  }

  toggleCollection(){
    if(!getRuntime().getToken()) { getRuntime().navigateTo('/pages/login/login'); return }
    let { userStore } = this.props.stores
    this.setState({
      isCollection: !this.state.isCollection
    }, () => {
      if(this.state.isCollection){
        // 收藏
        userStore.saveUserCollection({
          form: {
            dynamicsId:parseInt(this.$router.params.id),
            userCollectionType:0
          },
          callback: () => {
            this.setState({isTips: true, tipsText: '收藏成功~'})
          }
        })
      }else {
        // 取消收藏
        userStore.cancelUserCollection({
          form: {
            id: parseInt(this.$router.params.id),
            userCollectionType: 0,
          },
          callback: () => {
            this.setState({isTips: true, tipsText: '取消收藏成功~'})
          }
        })
      }
    })
  }

  getDynamicInfo(id) {
    let dynamicStore = this.props.stores.DynamicStore
    dynamicStore.getDynamicInfo({
      id,
      callback: res => {
        // console.log(res)
        let isCollection = parseInt(this.$router.params.isCollection) === 1 ? true : toJS(res.isCollection)
        this.setState({
          item: toJS(res),
          isCollection
        }, () => {
          this.share()
        })
      }
    })
  }

  handelRouter(url: string = '/pages/index/index'): void {
    getRuntime().navigateTo(url)
  }

  // 配置微信分享
  getJsApiParam = () => {
    let currentUrl = window.location.href
    let apiUrl = `${ServerHost}/api/Account/getWxJsApiParams?curUrl=${currentUrl}`
    Taro.showLoading({title: '加载中...'})
    fetch(apiUrl, {
      method: 'GET',
      mode: "cors",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      credentials: 'same-origin'
    })
      .then(response => {
        Taro.hideLoading()
        return response.json()
      })
      .then(response => {
        let appId = response.appId
        let timestamp = response.timestamp
        let nonceStr = response.nonceStr
        let signature = response.signature
        this.setState({ wxConfig: response })
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: appId, // 必填，公众号的唯一标识
          timestamp: timestamp, // 必填，生成签名的时间戳
          nonceStr: nonceStr, // 必填，生成签名的随机串
          signature: signature,// 必填，签名
          // jsApiList: ['updateAppMessageShareData','onMenuShareAppMessage'], // 必填，需要使用的JS接口列表
          jsApiList: 'updateAppMessageShareData,onMenuShareTimeline,onMenuShareAppMessage,onMenuShareQQ,onMenuShareWeibo'.split(',')
        });
      })
      .catch(error => {
        console.log(error)
      })
  }

  share() {
    // if(!getRuntime().getToken()) { getRuntime().navigateTo('/pages/login/login'); return }
    let { item } = this.state
    let url1 = ServerHost+'/m/#/pages/dynamic/detail?id='+item.id
    let title = item.title
    let desc = htmlToText(item.content)
    let imgUrl = item.logo
    // wxShare(title, desc,url1,imgUrl)
    var shareData = {
      title,
      desc,
      imgUrl,
      otherImgUrl: '',
      url: window.location.href,
      link: window.location.href
    };
    wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
      wx.onMenuShareTimeline(shareData);
      wx.updateAppMessageShareData(shareData);
      wx.onMenuShareQQ(shareData);
      wx.onMenuShareWeibo(shareData);
    });
   // WxShare(url,item.logo,item.title,partOf(item.content, 30))
  }

  btnShare() {
    this.setState({ isShare: true })
  }

  onClose() {
    this.setState({ isShare: false })
  }

  componentDidHide(): void {
    this.setState({ isShare: false })
  }

  render() {
    let { item,isCollection,isShare } = this.state
     return(
      <View className='article-wrap dynamic-article'>
       <View className='article-info'>
         <View className='title'>
           {item.title}
         </View>
         <Text className='source'>{item.author}</Text>
         <Text className='date'>{subtime(item.creationTime)}</Text>
       </View>
        <View className='article rich-text'>
          <RichText nodes={item.content} />
        </View>

        <View className='footer-block' />
        <View className='footer'>
          <View className='read-count'>{item.readAmount}次浏览</View>
          <View className='share'>
            <View className='collection' onClick={this.toggleCollection.bind(this)}>
              {!isCollection&&
                <View>
                   <Image  className='collection-img' src={iconCollection} />
                   <Text>收藏</Text>
                </View>
              }
              {isCollection&&
                <View>
                   <Image  className='collection-img' src={iconCollection_on} />
                   <Text>已收藏</Text>
                </View>
              }
            </View>
            <View className='collection' onClick={this.btnShare.bind(this)}>
              <Image className='share-img' src={iconShare} />
              分享
            </View>
          </View>
        </View>
        <View className='footer-block' />
        <View className='footer-block' />
        <View className={isShare?'share-arrow share-arrow-active':'share-arrow'}>
          <Image className='share-arrow-icon' src={share_icon} />
          <View className='con'>
            <View>请点击右上角</View>
            <View>通过【发送给朋友】</View>
            <View>分享给好友</View>
          </View>
          <Image className='close-icon' onClick={this.onClose.bind(this)} src={close_icon} />
        </View>
      </View>
    )
  }
}

export default Detail
